package com.doudou.collection.adapter.controller;



import com.doudou.collection.infrastructure.common.web.ResultVO;
import com.doudou.collection.utils.QiniuCloudUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 *@ClassName UploadController
 *@Description TODO
 *@Author Administrator
 *@Date 2023/6/28 0:28
 *@Version 1.0
 */


@Slf4j
@RestController
@RequestMapping("/v1/upload")
@Api(tags ="上传组件")
public class UploadController {

    @Autowired
    QiniuCloudUtil qiniuCloudUtil;

    public UploadController() {
        log.info("创建控制器对象：UploadController");
    }


    @ApiOperation("上传文章封面")
    @ApiOperationSupport(order = 110)
    @PostMapping("")
    public ResultVO uploadArticleImg(@RequestParam("file") MultipartFile image) {
        log.info("UploadController:正在上传文章封面");
        return ResultVO.ok(upload(image,"articleImg"));
    }

    @ApiOperation("上传用户头像")
    @ApiOperationSupport(order = 120)
    @PostMapping("/image/iconUrl")
    public ResultVO uploadUserIcon(@RequestParam("file") MultipartFile image){
        log.debug("UploadController:正在上传用户头像");

        return ResultVO.ok(upload(image,"iconUrl"));
    }



    private String upload(MultipartFile image,String type){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        if (image.isEmpty()) {
        }
        try {
            String dirName = simpleDateFormat.format(new Date());
            byte[] bytes = image.getBytes();
            String imageName = "resource/articleImg/" + type +dirName + "/" +UUID.randomUUID().toString();

            QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
            try {
                //使用base64方式上传到七牛云
                String url = qiniuUtil.put64image(bytes, imageName);
                return url;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "出错了";
        } catch (IOException e) {
            return "出错了";
        }
    }

}
